package xeroxware.framework;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import xeroxware.framework.exception.PermissionException;
import xeroxware.framework.util.CommonUtil;

/**
 * <pre>
 * VerifyPermissionInterceptor
 * </pre>
 * 
 * @since 2013. 1. 9.
 * @author XEROXER
 */
public class VerifyPermissionInterceptor extends HandlerInterceptorAdapter {

	@Value("#{contextProperties['application.real.flag']}")
	private String realFlag;

	@Autowired
	private MessageSourceAccessor msgSrcAccessor;

	private List<String> ignoreUrl;

	public List<String> getIgnoreUrl() {
		return ignoreUrl;
	}

	public void setIgnoreUrl(List<String> urls) {
		ignoreUrl = urls;
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		if (ignoreUrl.contains(request.getRequestURI()) || !"Y".equalsIgnoreCase(realFlag)) {
			return true;
		}

		HttpSession session = request.getSession(false);

		if (session == null || CommonUtil.isEmpty(session.getAttribute("userId"))) {
			throw new PermissionException(msgSrcAccessor.getMessage("msg.exception.invalid.access",
					new Object[] { request.getRequestURI() }));
		}

		return true;
	}
}
